﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Web.SystemLogin.Services;
using Web.SystemLogin.DataAccess;
using System.Data;
using Web.SystemLogin.Models;
using System.Web;
using DreamBuilder.Common;
using System.DirectoryServices;


namespace Web.SystemLogin.Business
{
    public class BUSSystemLogin : BusinessBase, ISystemLogin
    {
        DALSystemLogin dal;
        public BUSSystemLogin()
        {
            dal = new DALSystemLogin();
        }
        public string CheckLoginNameAvailable(string loginName)
        {
            DataTable dt = dal.CheckLoginNameAvailable(loginName);
            string userID = string.Empty;
            if (dt != null && dt.Rows.Count > 0)
            {
                userID = dt.Rows[0][0].ToString();
            }
            return userID;
        }
        public string CheckOALoginNameAvailable(string loginName)
        {
            DataTable dt = dal.CheckOALoginNameAvailable(loginName);
            string userID = string.Empty;
            if (dt != null && dt.Rows.Count > 0)
            {
                userID = dt.Rows[0][0].ToString();
            }
            return userID;
        }
        public string CheckCNPCLoginNameAvailable(string loginName)
        {
            DataTable dt = dal.CheckCNPCLoginNameAvailable(loginName);
            string userID = string.Empty;
            if (dt != null && dt.Rows.Count > 0)
            {
                userID = dt.Rows[0][0].ToString();
            }
            return userID;
        }
        public bool CheckUserPassword(string userID, string passwd)
        {
            DataTable dt = dal.CheckUserPassword(userID, passwd);
            bool result = false;
            if (dt != null && dt.Rows.Count > 0)
            {
                result = true;
            }
            return result;
        }
        public User GetCurrentUser(string userID)
        {
            DataTable dt = dal.GetCurrentUser(userID);
            User user = null;

            if (dt != null && dt.Rows.Count > 0)
            {
                user = this.LoadFromDataTable(dt);
            }
            else
            {
                throw new ApplicationException("User does not exist.");
            }
            return user;
        }

        protected User LoadFromDataTable(DataTable dt)
        {
            User user = new User();
            if (HttpContext.Current!=null)
            {
                user.SessionID = HttpContext.Current.Session.SessionID;
            }
            //初始状态下都是登陆人
            //User_ID表示实际权限用户ID
            user.User_ID = dt.Rows[0]["User_ID"].ToString();
            //Real_ID表示实际登录人ID
            user.Real_ID = dt.Rows[0]["User_ID"].ToString();
            //by lyn 20111101
            user.Real_Name = dt.Rows[0]["User_Name"].ToString();
            user.User_Name = dt.Rows[0]["User_Name"].ToString();
            user.ORG_ID = dt.Rows[0]["ORG_ID"].ToString();
            user.Login_ID = dt.Rows[0]["Login_ID"].ToString();
            user.Org_FullFondsNum = GetOrgFullFonds(user.User_ID);
            // modify by lyn 新增用户全部单位 
            user.All_Org_Name = GetUserAllOrgName(user.User_ID.ToString());
            user.Org_Name = GetUserOrgName(user.User_ID.ToString());
            if ( dt.Rows[0]["Last_Login_Time"]!=DBNull.Value)
            {
                user.Last_Login_Time = (DateTime)dt.Rows[0]["Last_Login_Time"];
            }
            if (dt.Rows[0]["This_Login_Time"] != DBNull.Value)
            {
                user.This_Login_Time = (DateTime)dt.Rows[0]["This_Login_Time"];
            }
            return user;
        }

        public void UpdateUserLoginInfo(string userID)
        {
            dal.UpdateUserLoginInfo(userID);
        }
        //add by lyn 20111229
        public bool ValidateUser(string ldapServer, string userAccount, string passWord, string domain)
        {
            int iPosition = userAccount.IndexOf(@"\");
            if (iPosition > 0)
            {
                userAccount = userAccount.Substring(iPosition + 1, (userAccount.Length - iPosition) - 1);
            }
            try
            {
                DirectoryEntry root;
                if (string.IsNullOrEmpty(ldapServer))
                {
                    root = new DirectoryEntry("WinNT://" + Environment.MachineName, userAccount, passWord);
                    root.Children.Find(userAccount, "User").Close();
                    root.Close();
                    return true;
                }
                if (!ldapServer.Trim().ToUpper().StartsWith("LDAP://"))
                {
                    ldapServer = "LDAP://" + ldapServer;
                }
                root = new DirectoryEntry(ldapServer, domain + @"\" + userAccount, passWord);
                DirectorySearcher search = new DirectorySearcher(root)
                {
                    Filter = string.Format("(SAMAccountName={0})", userAccount)
                };
                search.PropertiesToLoad.Add("name");
                search.FindOne().GetDirectoryEntry().Close();
                root.Close();
                return true;
            }
            catch (Exception e)
            {
                //logger.Error(e.Message);                
                return false;
            }
        }
        //add by lyn 20111229
        /// <summary>
        /// 登录用户验证，返回用户ID
        /// </summary>
        /// <param name="logonName"></param>
        /// <param name="pwd"></param>
        /// <param name="BizSystemID"></param>
        /// <param name="validateType"></param>
        /// <returns></returns>
        public bool ValiadateUserPWD(string logonName, string pwd, string validateType)
        {
            //string sql = string.Empty;
            bool isOK = false;
            //AD验证
            if (validateType == "AD")
            {
                string userId = CheckCNPCLoginNameAvailable(logonName);
                isOK = !string.IsNullOrEmpty(userId);
            }
            else if (validateType == "UserPwd")//UP验证
            {
                string userId = CheckCNPCLoginNameAvailable(logonName);
                isOK = CheckUserPassword(userId, pwd);
            }
            return isOK;
            //return string.Empty;
        }
        #region 更新CNPC用户名
        public void UpdateUserCNPCLoginName(string cnpcUserID, string loginName)
        {
            string strADPath = null;
            string strName = null;
            string strRealName = null;

            int iPosition = loginName.IndexOf(@"\");
            strADPath = loginName.Substring(0, iPosition);
            strName = loginName.Substring(iPosition + 1, loginName.Length - iPosition - 1);
            dal.UpdateUserCNPCLoginName(cnpcUserID, strName);
        }
        #endregion
        #region
        public string CNPCVerification(string userID)
        {
            DataTable dt = dal.GetCNPCVerification(userID);
            string UserDomain = string.Empty;
            if (dt != null && dt.Rows.Count > 0)
            {
                UserDomain = dt.Rows[0][0].ToString();
            }
            return UserDomain;
        }
        #endregion
        #region add by lyn 20111027
        public bool CheckCnpcLogin(string userID)
        {
            DataTable dt = dal.CheckCnpcLoginInfo(userID);
            bool result = false;
            if (dt != null && dt.Rows.Count > 0)
            {
                result = true;
            }
            return result;
        }
        #endregion
        #region add by lyn 20111101 得到全部所在单位名称
        public string GetUserAllOrgName(string userID)
        {
            DataTable userAllOrgName = dal.GetUserAllOrgNameInfo(userID);
            StringBuilder orgNameStr = new StringBuilder();
            if (userAllOrgName != null && userAllOrgName.Rows.Count > 0)
            {
                for (int i = userAllOrgName.Rows.Count - 1; i >= 0; i--)
                {
                    orgNameStr.Append(userAllOrgName.Rows[i]["ORG_Name"].ToString() + "-");
                }
            }
            return orgNameStr.ToString();
        }
        #endregion
        #region add by lyn 20120105 得到用户所在单位名称
        /// <summary>
        /// 得到用户所在单位名称
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <returns>单位名称</returns>
        public string GetUserOrgName(string userID)
        {
            DataTable dt = dal.GetUserOrgNameInfo(userID);
            string orgName = string.Empty;
            if (dt != null && dt.Rows.Count > 0)
            {
                orgName = dt.Rows[0][0].ToString();
            }
            return orgName;
        }
        #endregion

        #region add by guoyin 20121225 得到用户所在机构的全宗号
        /// <summary>
        /// 得到用户所在单位名称
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <returns>单位名称</returns>
        public string GetOrgFullFonds(string userID)
        {
            DataTable dt = dal.GetUserOrgFullFondsInfo(userID);
            string orgName = string.Empty;
            if (dt != null && dt.Rows.Count > 0)
            {
                orgName = dt.Rows[0][0].ToString();
            }
            return orgName;
        }
        #endregion
        #region add by guoyin
        public string GetUserIdByLoginId(string loginId)
        {
            return dal.GetUserIdByLoginId(loginId);
        }
        #endregion

        public bool UpdateUserPassword(string loginname, string password)
        {
            return dal.UpdateUserPassword(loginname, password);
        }
    }
}
